<script setup>
import { onMounted, reactive, ref, toRaw } from 'vue'
import { onBeforeRouteUpdate } from 'vue-router'
import router from '@/router'
import {
  getUsersByGroupIdAndStationIdApi,
  getUsersByGroupIdApi,
  postAddMemberApi,
  postRemoveMemberByUsernameApi,
  postUpdateMemberApi
} from '@/apis/user'
import { getStationListByGroupIdApi } from '@/apis/station'
import { getUserInfoByGroupIdAndNameApi } from '@/apis/department'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getCurrentRouteQuery } from '@/utils/routerUtils'

// 分页参数
const pageParam = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
// 岗位信息
const stationInfo = ref()
// 多选 （待开发）
const multipleTableRef = ref()
// 表格数据
const tableData = ref([])
const tableLoading = ref(false)

// 根据用户组id获取用户
const getUsersByGroupId = groupId => {
  tableLoading.value = true
  getUsersByGroupIdApi(groupId, pageParam.value.pageNum, pageParam.value.pageSize)
      .then(({data}) => {
        console.log(data)
        tableData.value = data.records || []
        pageParam.value.total = data.total
        // 重新获取当前组的岗位
        getStationListByGroupId()
      })
      .finally(() => {
        tableLoading.value = false
      })
}

// 处理切换当前页操作
const handleCurrentChange = val => {
  pageParam.value.pageNum = val
  getUsersByGroupId(getCurrentRouteQuery().groupId)
}

// 根据组ID获取岗位列表
const getStationListByGroupId = () => {
  getStationListByGroupIdApi(
      getCurrentRouteQuery().groupId,
      pageParam.value.pageNum,
      pageParam.value.pageSize
  ).then(({data}) => {
    stationInfo.value = data.dataList
  })
}

// 用户姓名
const nameInputRef = ref('')
// 根据姓名模糊查询
const searchByName = () => {
  tableLoading.value = true
  getUserInfoByGroupIdAndNameApi(getCurrentRouteQuery().groupId, nameInputRef.value)
      .then(({data}) => {
        tableData.value = data.records
        pageParam.value.total = data.total
      })
      .finally(() => (tableLoading.value = false))
}

// 岗位id
const stationId = ref('')
// 根据岗位信息获取成员信息
const getUserInfoByStationId = () => {
  tableLoading.value = true
  getUsersByGroupIdAndStationIdApi(
      getCurrentRouteQuery().groupId,
      stationId.value,
      pageParam.value.pageNum,
      pageParam.value.pageSize
  )
      .then(({data}) => {
        tableData.value = data.records
      })
      .finally(() => {
        tableLoading.value = false
      })
}

// 用户信息对话框
const userInfoDialogVisible = ref(false)
const userInfoDiaglogTip = ref()
const userInfoFormRef = ref()
const userInfoOption = ref()
const userInfoForm = reactive({
  data: {
    groupId: '', // 通过当前路径参数获取
    name: '', // 用户名 中文
    username: '', // 花名 英文
    aliasName: '', // 花名 中文
    stuId: '', // 学号
    sex: '', // 性别
    stationId: '', // 岗位ID
    age: 1, // 年龄
    school: '', // 学校
    academy: '', // 学院
    grade: '' // 年级
  }
})
const userInfoRule = ref({
  name: [{required: true, message: '请输入姓名（中文）', tigger: 'blur'}],
  stuId: [
    // { required: true, message: '请输入学号', tigger: 'blur' },
    // { min: 0, message: '学号不能为空', tigger: true }
  ],
  username: [
    {required: true, message: '请输入英文花名', tigger: 'blur'},
    {
      pattern: '[a-zA-Z]+',
      message: '必须为英文字母',
      tigger: 'blur'
    }
  ],
  aliasName: [
    {required: true, message: '请输入中文花名', tigger: 'blur'},
    {min: 2, max: 2, message: '中文花名必须为2个字符', tigger: 'blur'}
  ]
})

// 提交信息表格
const submitUserInfoForm = formEl => {
  formEl.validate(valid => {
    if (valid) {
      userInfoForm.data.groupId = getCurrentRouteQuery().groupId
      // 上传信息
      if ('add' == userInfoOption.value) addUser()
      else if ('update' == userInfoOption.value) updateUser()
    }
  })
}

// 添加成员
const addUser = () => {
  postAddMemberApi(toRaw(userInfoForm).data)
      .then(() => {
        ElMessage({type: 'success', message: '新增成员成功'})
        getUsersByGroupId(getCurrentRouteQuery().groupId)
      })
      .catch(() => {
        ElMessage({type: 'error', message: '新增成员失败，请重新尝试'})
      })
}

// 更新成员
const updateUser = () => {
  postUpdateMemberApi(toRaw(userInfoForm).data)
      .then(() => {
        ElMessage({type: 'success', message: '编辑成员信息成功'})
        getUsersByGroupId(getCurrentRouteQuery().groupId)
      })
      .catch(() => {
        ElMessage({type: 'error', message: '编辑成员信息失败，请重新尝试'})
      })
}

// 删除成员
const removeMember = data => {
  ElMessageBox.confirm(`确定删除 "<font color="red">${ data.name }</font>" 成员？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    dangerouslyUseHTMLString: true,
    type: 'warning'
  })
      .then(() => {
        postRemoveMemberByUsernameApi(data)
            .then(() => {
              getUsersByGroupId(getCurrentRouteQuery().groupId)
              ElMessage({type: 'success', message: '删除成员成功'})
            })
            .catch(err => {
              ElMessage({type: 'error', message: '删除成员失败，请重新尝试'})
            })
      })
      .catch(() => {
        ElMessage({type: 'info', message: '已取消删除'})
      })
}

// 生成年级数据
const generateGrade = () => {
  const year = new Date().getFullYear()
  const grade = []
  for (let i = year - 4; i <= year; i++) {
    grade.push(i + '级')
  }
  return grade
}

// 面包屑
const breadList = ref([{name: '部门管理', path: '/system/department'}])

// 编辑成员
const updateUserInfoInTable = (index, data) => {
  userInfoDiaglogTip.value = '编辑用户'
  userInfoDialogVisible.value = true
  // 表单赋值
  userInfoForm.data = data
  // 映射岗位
  userInfoForm.data.stationId = stationInfo.value.filter(item => item.stationName == data.stationName)[0].id
}

const handleSelectionChange = val => {
  multipleSelection.value = val
}

// 路由
onBeforeRouteUpdate(to => {
  // 判断是否为数字
  if (/^[0-9]*$/.test(to.query.groupId)) {
    getUsersByGroupId(to.query.groupId)
  } else {
    router.back()
    // ElMessage({ type: 'warning', message: '组id不正确' })
  }
})

onMounted(() => {
  // 当不是访问的当前路径的根路径时
  if (getCurrentRouteQuery().groupId != undefined) getUsersByGroupId(getCurrentRouteQuery().groupId)
})
</script>

<template>
  <el-breadcrumb separator="/" style="margin-bottom: 20px">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <template v-for="(item, index) in breadList">
      <el-breadcrumb-item v-if="item.name" :key="index" :to="item.path">{{ item.name }}</el-breadcrumb-item>
    </template>
  </el-breadcrumb>
  <el-row :gutter="20">
    <el-col :span="4">
      <el-select v-model="stationId" @change="getUserInfoByStationId" placeholder="请选择岗位">
        <el-option label="全部岗位" value="" />
        <el-option v-for="station in stationInfo" :key="station.id" :label="station.stationName" :value="station.id" />
      </el-select>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="4">
      <el-input v-model="nameInputRef" placeholder="请输入姓名搜索" />
    </el-col>
    <el-col :span="1.5">
      <el-button type="primary" :icon="Search" @click="searchByName">搜索</el-button>
    </el-col>
    <el-col :span="4">
      <el-button
          type="primary"
          :icon="Plus"
          @click=";(userInfoDiaglogTip = '新增用户'), (userInfoDialogVisible = true), (userInfoOption = 'add')"
      >新增成员
      </el-button
      >
    </el-col>
  </el-row>
  <el-table
      v-loading="tableLoading"
      ref="multipleTableRef"
      :data="tableData"
      height="500"
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <!-- <el-table-column label="Date" width="120">
      <template #default="scope">{{ scope.row.date }}</template>
    </el-table-column> -->
    <el-table-column property="name" label="姓名" width="100" />
    <el-table-column property="aliasName" label="中文花名" width="80" />
    <el-table-column property="stuId" label="学号" width="130" />
    <el-table-column property="age" label="年龄" width="80" />
    <el-table-column property="sex" label="性别" width="80" />
    <el-table-column property="stationName" label="岗位" width="200" />
    <el-table-column property="school" label="公司" width="120" />
    <el-table-column property="academy" label="部门" width="180" />
    <el-table-column property="grade" label="类型" width="120" />
    <el-table-column fixed="right" label="操作" width="160">
      <template #default="scope">
        <el-button type="primary" @click=";(userInfoOption = 'update'), updateUserInfoInTable(scope.$index, scope.row)"
        >编辑
        </el-button
        >
        <el-button type="danger" @click="removeMember(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination background layout="prev, pager, next" :total="pageParam.total" @current-change="handleCurrentChange" />

  <el-dialog v-model="userInfoDialogVisible" :title="userInfoDiaglogTip" width="30%">
    <el-form ref="userInfoFormRef" :model="userInfoForm.data" :rules="userInfoRule">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userInfoForm.data.name" autocomplete="off" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="stuId">
            <el-input
                v-model="userInfoForm.data.stuId"
                :disabled="userInfoOption == 'update'"
                autocomplete="off"
                placeholder="请输入学号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="英文花名" prop="username">
            <el-input
                v-model="userInfoForm.data.username"
                :disabled="userInfoOption == 'update'"
                autocomplete="off"
                placeholder="请输入英文花名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中文花名" prop="aliasName">
            <el-input
                v-model="userInfoForm.data.aliasName"
                :disabled="userInfoOption == 'update'"
                autocomplete="off"
                placeholder="请输入中文花名"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别">
            <el-select v-model="userInfoForm.data.sex" placeholder="请选择性别">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input-number v-model="userInfoForm.data.age" :min="1" :max="120" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="岗位">
            <el-select v-model="userInfoForm.data.stationId" placeholder="请选择岗位">
              <el-option
                  v-for="station in stationInfo"
                  :key="station.id"
                  :label="station.stationName"
                  :value="station.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司">
            <el-input v-model="userInfoForm.data.school" autocomplete="off" placeholder="请输入公司" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="部门">
            <el-input v-model="userInfoForm.data.academy" autocomplete="off" placeholder="请输入部门" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型">
            <el-select v-model="userInfoForm.data.grade" placeholder="请选择类型">
              <el-option label="正式" value="正式" />
              <el-option label="实习" value="实习" />
              <!--              <el-option v-for="(grade, index) in generateGrade()" :key="index" :label="grade" :value="grade" />-->
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUserInfoForm(userInfoFormRef)"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 40px;
}
</style>
